package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.entity.RoleUserMap;
import com.example.demo.entity.UserRole;
import com.example.demo.mapper.RoleUserMapMapper;
import com.example.demo.service.RoleService;
import com.example.demo.service.RoleUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class RoleUserServiceImpl implements RoleUserService {
    @Resource
    RoleUserMapMapper roleUserMapMapper;

    @Override
    public Result<?> addRoleToUser(List<UserRole> userRoleList) {
        if (oneRoleToUser(userRoleList).size()>0){
            return Result.error("repect","请勿重复添加用户");
        }
        RoleUserMap roleUserMap = new RoleUserMap();
        for (int i=0; i<userRoleList.size(); i++){
            roleUserMap.setCreateBy(userRoleList.get(i).getCreateBy());
            roleUserMap.setUserId(userRoleList.get(i).getId());
            roleUserMap.setRolesId(userRoleList.get(i).getRoleId());
            roleUserMap.setDeleted(0);
            roleUserMapMapper.insert(roleUserMap);
        }
        return Result.success();
    }

    public List<RoleUserMap> oneRoleToUser(List<UserRole> userRoleList){
        int[] ids = new int[userRoleList.size()];
        for (int i=0; i<userRoleList.size();i++){
            ids[i] = userRoleList.get(i).getId();
        }
        Integer roleId = userRoleList.get(0).getRoleId();
        List<RoleUserMap> roleUserMaps = roleUserMapMapper.oneRoleToUser(ids,roleId);
        return roleUserMaps;
    }

    @Override
    public Result<?> deleteRoleToUser(List<UserRole> userRoleList) {
        RoleUserMap roleUserMap = new RoleUserMap();
        for (int i=0; i<userRoleList.size(); i++){
            roleUserMapMapper.deleteRoleToUser(userRoleList.get(i).getCreateBy(),userRoleList.get(i).getId(),userRoleList.get(i).getRoleId());
        }
        return Result.success();
    }

}
